package com.dhcc.bpm.business.papc.service.impl;

import com.dhcc.bpm.business.papc.entity.JobInfo;
import com.dhcc.bpm.business.papc.vo.JobInfoVO;
import com.dhcc.bpm.business.papc.mapper.JobInfoMapper;
import com.dhcc.bpm.business.papc.service.IJobInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhcc.bpm.modules.common.vo.SelectsVo;
import org.quartz.*;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.util.ArrayList;
import java.util.List;

/**
 *  服务实现类
 *
 * @author sjm
 * @since 2020-12-11
 */
@Service
public class JobInfoServiceImpl extends ServiceImpl<JobInfoMapper, JobInfo> implements IJobInfoService {

	@Override
	public IPage<JobInfoVO> selectJobInfoPage(IPage<JobInfoVO> page, JobInfoVO jobInfo) {
		return page.setRecords(baseMapper.selectJobInfoPage(page, jobInfo));
	}

	@Override
	public List<SelectsVo> selectJobinfoName() {
		return baseMapper.selectJobinfoName();
	}

	@Override
	public JobInfo getJobEntityById(Integer id) {
		JobInfo job = baseMapper.findJobById(id);
		if (job != null) {
			return job;
		}
		return null;
	}
	//获取JobKey,包含Name和Group
	@Override
	public JobKey getJobKey(JobInfo job) {
		return JobKey.jobKey(job.getName(), job.getGroupName());
	}
	
	//获取JobDataMap.(Job参数对象)
	@Override
	public JobDataMap getJobDataMap(JobInfo job) {
		JobDataMap map = new JobDataMap();
		map.put("name", job.getName());
		map.put("group", job.getGroupName());
		map.put("cronExpression", job.getCron());
		map.put("parameter", job.getParameter());
		map.put("JobDescription", job.getDescription());
		map.put("vmParam", job.getVmParam());
		map.put("status", job.getStatus());
		return map;
	}
	
	//获取JobDetail,JobDetail是任务的定义,而Job是任务的执行逻辑,JobDetail里会引用一个Job Class来定义
	@Override
	public JobDetail geJobDetail(JobKey jobKey, String description, JobDataMap map, String className) {
		Class<?> jobExecuteClass = null;
		try {
			jobExecuteClass = Class.forName(className);
		} catch (ClassNotFoundException e) {
			System.out.println(className + "ClassNotFound,"+ e.getMessage());
			return null;
		}
		return JobBuilder.newJob((Class<? extends Job>) jobExecuteClass)
				.withIdentity(jobKey)
				.withDescription(description)
				.setJobData(map)
				.storeDurably()
				.build();
	}

	//获取Trigger (Job的触发器,执行规则)
	@Override
	public Trigger getTrigger(JobInfo job) {
		return TriggerBuilder.newTrigger()
				.withIdentity(job.getName(), job.getGroupName())
				.withSchedule(CronScheduleBuilder.cronSchedule(job.getCron()))
				.build();
	}
	//从数据库中加载获取到所有Job
	@Override
	public List<JobInfo> loadJobs() {
		List<JobInfo> list = new ArrayList<>();
		List<JobInfo> jobList = baseMapper.findAll();
		for (JobInfo job : jobList) {
			list.add(job);
		}
		return list;
	}
	@Override
	public List<Integer> getGroupNameNum() {
		return baseMapper.getGroupNameNum();
	}

}
